package cn.littlehx.myweb.api;

import cn.littlehx.myweb.common.MailRequest;
import cn.littlehx.myweb.common.R;
import cn.littlehx.myweb.domain.User;
import cn.littlehx.myweb.service.ICaptchaService;
import cn.littlehx.myweb.service.ISendMailService;
import cn.littlehx.myweb.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/index/user/login")
public class LoginApiController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ISendMailService mailService;
    @Autowired
    private ICaptchaService captchaService;



    @PutMapping("/captcha")
    public R getCaptcha(@RequestBody User user){
        String email = user.getEmail();
        if(userService.selectByEmail(email)!=null){
            return new R(false, null,"邮箱已注册");
        }
       //生成并保存验证码
        String captcha = captchaService.generateCaptcha(email);
        String text = String.format("验证码为: %s",captcha);

        //发送邮件
        MailRequest mailRequest = new MailRequest(email,"欢迎注册我们的网站",text);
        mailService.sendSimpleMail(mailRequest);
        return new R(true,captcha,"发送验证码成功");
    }

    /**
     * 存储用户信息和
     * @param jsonObject
     * @return
     */
    //因为不是幂等操作,所以用post方法
    @PostMapping("/register")
    public R register(@RequestBody JSONObject jsonObject){
        String captcha = (String) jsonObject.get("captcha");
        User user = new User();
        user.setEmail((String) jsonObject.get("email"));
        user.setPassword((String) jsonObject.get("password"));
        Integer age = Integer.parseInt(String.valueOf(jsonObject.get("age")));
        Integer sex = Integer.parseInt(String.valueOf(jsonObject.get("sex")));
        user.setUsername((String) jsonObject.get("username"));

        //判断验证码是否正确
        if(!captchaService.confirmCaptcha(user.getEmail(), captcha)) {
            return new R(false,null,"验证码错误或已过期");
        }

        //新增进用户表
        boolean flag = userService.save(user);
        if(flag){
            log.info("验证码为{}",captcha);
            return new R(true,null);
        }
        else {
            log.info("验证码为{}",captcha);
            return new R(false,null,"不可输入重复邮箱");
        }

    }

    /**
     * 按照邮箱和密码进行查找
     * @param user
     * @return
     */
    @PostMapping
    public R login(@RequestBody User user, HttpServletRequest request){
        User userReturned = userService.selectByEmailAndPassword(user.getEmail(), user.getPassword());
        if(userReturned!=null){
            userReturned.setPassword("");
            //存入session
            request.getSession().setAttribute("userId",userReturned.getId());
            return new R(true,userReturned,"返回数据成功");
        }else {
            return new R(false,null,"邮箱或者密码不正确");
        }
    }
    @PutMapping
    public R update(@RequestBody User user){
        //通过邮箱查找该用户
        User userGot = userService.selectByEmail(user.getEmail());
        if(userGot == null){
            return new R(false,null,"查无此人,请检查邮箱是否正确");
        }
        user.setId(userGot.getId());
        boolean flag = userService.updateById(user);
        if(flag){
            return new R(true,null,"修改成功");
        }else {
            return new R(false,null,"服务器出错,请稍后重试");
        }

    }
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        log.info("用户 "+request.getSession().getAttribute("userId")+" 已经退出");
        //清理session中的员工id
        request.getSession().removeAttribute("userId");
        return new R(true,null,"退出成功");
    }


}
